package com.ala4.oxcafe.boot.aop;

import com.ala4.oxcafe.common.utils.IpAddressUtil;
import com.ala4.oxcafe.common.utils.text.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 系统统计服务
 *
 * @author PING
 * @version 1.0.0
 * @date 2025/8/18 11:19
 */
@Service
public class VisitCounterService {

    /**
     * 访问人数
     */
    public static final String BIZ_TYPE_VISITOR_COUNT = "visitor_count";
    private static final String UV_PREFIX = "uv:ip:";
    private final RedisTemplate<String, String> redisTemplate;

    public VisitCounterService(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 记录访问（自动从Request获取IP）
     *
     * @param request HTTP请求对象
     * @param bizType 业务类型
     */
    public void recordVisit(HttpServletRequest request, String bizType) {
        String ip = IpAddressUtil.getClientIp(request);
        if (StrUtil.isEmpty(ip)) {
            return;
        }

        String key = buildDailyKey(bizType);
        redisTemplate.opsForHyperLogLog().add(key, ip);
        redisTemplate.expire(key, 48, TimeUnit.HOURS); // 保留48小时（跨天处理）
    }

    /**
     * 获取当日去重IP访问量
     */
    public Long getDailyVisitCount(String bizType) {
        return redisTemplate.opsForHyperLogLog().size(buildDailyKey(bizType));
    }


    private String buildDailyKey(String bizType) {
        return UV_PREFIX + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + ":" + bizType;
    }

}
